package com.xxiongb.login.config;

import java.util.Arrays;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;

import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;

@Configuration
@PropertySource(value = { "classpath:mongodb.properties" })
public class MongoConfiguration extends AbstractMongoConfiguration{

	@Autowired
	private Environment env = null;
	
	@Bean
	@Override
	public MongoDbFactory mongoDbFactory() throws Exception {
		MongoClient mc = (MongoClient)mongo();
		return new SimpleMongoDbFactory(mc, "xxiongb");
	}

	@Bean
	public MongoTemplate mongoTemplate() throws Exception {
		return new MongoTemplate(mongoDbFactory());
	}

	@Override
	protected String getDatabaseName() {
		return env.getProperty("mongo.collect");
	}

	@Override
	protected String getMappingBasePackage() {
		return "com.xxiongb.login.repository.entity";
	}
	
	@Override
	public Mongo mongo() throws Exception {
		MongoCredential credential = MongoCredential.createCredential("yiyi", "xxiongb", "yy123".toCharArray());
		ServerAddress serverAddr = new ServerAddress("127.0.0.1");
		MongoClient client = new MongoClient(serverAddr, Arrays.asList(credential));
		return client;
	}

}
